package com.example.security1.config.security.handler;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.example.security1.config.exception.CustomerAuthenticationException;
import com.example.security1.util.vo.ResultVO;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component("loginFailureHandler")
public class LoginFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        int code = 500;
        String str;
        if(exception instanceof AccountExpiredException){
            str = "账户过期，登录失败!";
        }else if(exception instanceof BadCredentialsException){
            // BadCredentialsException 继承于 AuthenticationException
            str = "用户名或密码错误，登录失败!";
        }else if(exception instanceof CredentialsExpiredException){
            str = "密码过期，登录失败!";
        }else if(exception instanceof DisabledException){
            str = "账户被禁用，登录失败!";
        }else if(exception instanceof LockedException){
            str = "账户被锁，登录失败!";
        }else if(exception instanceof InternalAuthenticationServiceException){
            str = "账户不存在，登录失败!";
        }else if(exception instanceof CustomerAuthenticationException){
            code = 600;
            str = exception.getMessage();
        }else{
            str = "登录失败!";
        }
        // 返回json
        // SerializerFeature.DisableCircularReferenceDetect 消除循环引用
        String res = JSONObject.toJSONString(new ResultVO<>(str, code, null), SerializerFeature.DisableCircularReferenceDetect);
        // 设置返回格式
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(res.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
